package org.meow.handler;

import lombok.extern.slf4j.Slf4j;
import org.meow.constant.MsgConstant;
import org.meow.constant.ResCode;
import org.meow.exception.AuthException;
import org.meow.exception.BaseException;
import org.meow.result.Result;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * &#064;Date: 24/04/22-18:14
 * &#064;Description:
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

  /**
   * 处理业务异常
   *
   * @param ex 异常对象
   * @return Result
   */
  @ExceptionHandler
  public Result<String> exceptionHandler(BaseException ex) {
    log.error("异常信息：{}", ex.getMessage());
    return Result.error(ex.getMessage());
  }

  @ExceptionHandler
  public Result<String> exceptionHandler(AuthException ex) {
    log.info("异常信息：{}", ex.getMessage());
    return Result.error(ResCode.UNAUTHORIZED, ex.getMessage());
  }

  @ExceptionHandler
  public Result<String> exceptionHandler(Exception ex) {
    log.error("异常信息：{}", ex.getMessage());
    return Result.error(ResCode.INTERNAL_SERVER_ERROR, ex.getMessage());
  }

  /**
   * 处理SQL完整性异常
   */
  @ExceptionHandler
  public Result<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
    // Duplicate entry 'xx' for key 'xx'
    String message = ex.getMessage();
    if (message.contains("Duplicate entry")) {
      String[] split = message.split(" ");
      String   entry = split[2];
      String   msg   = entry + MsgConstant.ALREADY_EXISTS;
      return Result.error(msg);
    } else {
      return Result.error(MsgConstant.UNKNOWN_ERROR);
    }
  }

}
